package com.greyshark.lib.bluetooth.utils

import android.Manifest
import android.app.Notification
import android.app.Service
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ServiceInfo
import android.os.Build
import androidx.core.content.ContextCompat
import com.greyshark.lib.bluetooth.core.internal.NotificationUtils

class CreateNotificationUtils {

  private val tag = CreateNotificationUtils::class.java.simpleName

  companion object {
    val instance: CreateNotificationUtils by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
      CreateNotificationUtils()
    }
  }

  var notification: Notification? = null
    private set

  var notificationId: Int = 0
    private set

  fun startForeground(
    service: Service,
    notificationTitle: String,
    notificationText: String,
    notifyAppIcon: Int
  ) {
    try {
      if (notificationTitle.isNotEmpty() && notificationText.isNotEmpty()) {
        val intent = Intent(service, NotificationClickReceiver::class.java)
        intent.setAction(NotificationClickReceiver.CLICK_NOTIFICATION)

        val notification = NotificationUtils.createNotification(
          service,
          notificationTitle,
          notificationText,
          notifyAppIcon,
          intent
        )

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
          if (ContextCompat.checkSelfPermission(
              service, Manifest.permission.BLUETOOTH_SCAN
            ) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(
              service, Manifest.permission.BLUETOOTH_CONNECT
            ) == PackageManager.PERMISSION_GRANTED
          ) {
            service.startForeground(
              javaClass.hashCode(),
              notification,
              ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
            )
          }
        } else {
          service.startForeground(javaClass.hashCode(), notification)
        }

        this.notification = notification
        this.notificationId = javaClass.hashCode()
      }
    } catch (e: Exception) {
      BleLogger.e(tag, "startForgeGround exception :${e.message}")
    }
  }

  fun removeNotification(service: Service) {
    service.stopForeground(true)
  }

  /*
  @SuppressLint(
    "WrongConstant",
    "LaunchActivityFromNotification",
    "UnspecifiedImmutableFlag"
  )
  class NotificationUtils(
    private val context: Context
  ) : ContextWrapper(context) {

    private var manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager

    companion object {

      private val id: String = "channel_ble_service"
      private val name: String = "ble_service"

      @RequiresApi(api = Build.VERSION_CODES.O)
      fun createNotificationChannel() {
        val channel = NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH)
        manager.createNotificationChannel(channel)
      }

      @RequiresApi(api = Build.VERSION_CODES.O)
      private fun getChannelNotification(
        title: String?,
        content: String?,
        icon: Int,
        intent: Intent?
      ): Notification.Builder {
        val notificationBuilder = Notification.Builder(context, id)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
          //从 Android 12 系统开始，前台服务通知默认会延迟 10 s 显示，修改为立即显示通知
          notificationBuilder.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE)
        }
        notificationBuilder.setContentTitle(title)
          .setContentText(content)
          .setSmallIcon(icon)
          .setLargeIcon(
            BitmapFactory.decodeResource(
              baseContext.resources,
              baseContext.applicationInfo.icon
            )
          )
          .setAutoCancel(true)
          .setOngoing(true)
        if (intent != null) {
          val pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            //Android13适配时报下面错误：
            //java.lang.IllegalArgumentException: android: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
            PendingIntent.getBroadcast(
              context,
              0,
              intent,
              PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
            )
          } else {
            PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
          }
          notificationBuilder.setContentIntent(pendingIntent)
        }
        return notificationBuilder
      }

      private fun getNotification25(
        title: String?,
        content: String?,
        icon: Int,
        intent: Intent?
      ): NotificationCompat.Builder {
        val notificationBuilder: NotificationCompat.Builder =
          NotificationCompat.Builder(context, id)
        notificationBuilder.setContentTitle(title)
          .setContentText(content)
          .setSmallIcon(icon)
          .setLargeIcon(
            BitmapFactory.decodeResource(
              baseContext.resources,
              baseContext.applicationInfo.icon
            )
          )
          .setAutoCancel(true)
          .setOngoing(true)
          .setVibrate(longArrayOf(0))
        if (intent != null) {
          val pendingIntent = PendingIntent.getBroadcast(
            context,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT
          )
          notificationBuilder.setContentIntent(pendingIntent)
        }
        return notificationBuilder
      }

      fun createNotification(
        context: Context,
        title: String?,
        content: String?,
        icon: Int,
        intent: Intent?
      ): Notification {
        val notificationUtils = NotificationUtils(context)
        var notification: Notification
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          notificationUtils.createNotificationChannel()
          notification =
            notificationUtils.getChannelNotification(title, content, icon, intent).build()
        } else {
          notification = notificationUtils.getNotification25(title, content, icon, intent).build()
        }
        return notification
      }


      /**
       * APP通知权限是否打开
       */
      fun areNotificationsEnabled(context: Context): Boolean {
        return NotificationManagerCompat.from(context).areNotificationsEnabled()
      }

      /**
       * 去到系统通知设置页面
       */
      fun goToSetNotification(context: Activity, requestCode: Int) {
        try {
          val intent = Intent()
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //这种方案适用于 API 26, 即8.0（含8.0）以上可以用
            intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
            intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
            intent.putExtra(Notification.EXTRA_CHANNEL_ID, context.applicationInfo.uid)
          } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //这种方案适用于 API21——25，即 5.0——7.1 之间的版本可以使用
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS")
            intent.putExtra("app_package", context.packageName)
            intent.putExtra("app_uid", context.applicationInfo.uid)
          } else {
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            intent.addCategory(Intent.CATEGORY_DEFAULT)
            intent.setData("package:${context.packageName}".toUri())
          }
          context.startActivityForResult(intent, requestCode)
        } catch (e: Exception) {
          e.printStackTrace()
          try {
            // 出现异常则跳转到应用设置界面：
            val intent = Intent()
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            val uri = Uri.fromParts("package", context.packageName, null)
            intent.setData(uri)
            context.startActivity(intent)
          } catch (e: Exception) {
            e.printStackTrace()
          }
        }
      }
    }
  }
   */
}

